package cn.jinjimi.app.custom.ui.fragment;

import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.jinjimi.base.Task.TaskExecutor;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceSelector;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.controller.event.LocalEvent.CustomAllTopEvent;
import cn.jinjimi.app.custom.iview.CustomersView;
import cn.jinjimi.app.custom.ui.view.CustomGuideView;
import cn.jinjimi.app.managers.NoticeManager;
import cn.jinjimi.app.presenter.CustomersPresenter;
import cn.jinjimi.app.store.entity.NoticeEntity;
import cn.jinjimi.app.main.adapter.FragmentPageAdapter;
import cn.jinjimi.app.main.extend.BaseFragment;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;


/**
 * 客户
 * Created by jinsen on 15/10/21.
 */
public class CustomerFragment extends BaseFragment implements CustomersView {

    public static final int PAGER_ALL = 0;
    public static final int PAGER_REMIND = 1;

    private TextView tvAllCustom;
    private TextView tvRemind;

    private ImageView imgRemindNotice;

    private ViewPager mViewPage;
    private FragmentPageAdapter mAdapter;

    private CustomGuideView mGuideView;
    private RelativeLayout mRootView;

    private Integer mCurPager;
    private Integer selectePosition;

    private CustomersPresenter customersPresenter;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_customer_layout;
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();

        if (getActivity().getIntent().hasExtra(BundleKey.SECPOSITION)) {
            String secPositionStr = getActivity().getIntent().getStringExtra(BundleKey.SECPOSITION);
            try {
                selectePosition = Integer.parseInt(secPositionStr);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            setSelectPosition(selectePosition);
        }
    }

    protected void initView() {
        mRootView = (RelativeLayout) findView().findViewById(R.id.customer_root_layout);

        tvAllCustom = (TextView) findView().findViewById(R.id.customer_all);
        tvRemind = (TextView) findView().findViewById(R.id.customer_remind);

        imgRemindNotice = (ImageView) findView().findViewById(R.id.bigday_red_icon);
        mViewPage = (ViewPager) findView().findViewById(R.id.viewpager);

    }

    protected void initListener() {
        tvAllCustom.setOnClickListener(this);
        tvRemind.setOnClickListener(this);
        findView().findViewById(R.id.btn_left).setOnClickListener(this);
        mViewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                showPager(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    protected void initData() {
        initFragment();

        if (selectePosition != null && selectePosition == 1)
            showPager(selectePosition);
        else
            showPager(PAGER_ALL);

        customersPresenter = new CustomersPresenter(this);
    }

    private void initFragment() {
        if (checkActivityExit())
            return;
        if (mAdapter != null) {
            mAdapter.removeAll();
        }
        mAdapter = new FragmentPageAdapter(getChildFragmentManager(), getFragmentList());
        mViewPage.setAdapter(mAdapter);
    }

    /**
     * 新建每个fragment，放到list中，通过PageAdapter进行获取显示
     *
     * @return
     */
    private List<BaseFragment> getFragmentList() {
        List<BaseFragment> fragmentList = new ArrayList<>();
        fragmentList.add(new CustomerAllFragment());
        fragmentList.add(new CustomRemindFragment());
        return fragmentList;
    }

    /* 由外界决定显示那个fragment */
    private void setSelectPosition(Integer selectePosition) {
        this.selectePosition = selectePosition;
        if (selectePosition != null) {
            if (mViewPage != null) {
                showPager(selectePosition);
                this.selectePosition = null;
            }
        }
    }

    @Override
    public void showGuideView() {
        if (mGuideView == null) {
            mGuideView = new CustomGuideView(getActivity());
        }
        mRootView.removeView(mGuideView);
        mRootView.addView(mGuideView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mViewPage.setVisibility(View.INVISIBLE);
    }

    @Override
    public void hideGuideView() {
        mRootView.removeView(mGuideView);
        mViewPage.setVisibility(View.VISIBLE);
        setUserVisibleHint(getUserVisibleHint());
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (mAdapter != null && mViewPage != null) {
            if (mCurPager == PAGER_ALL)
                mAdapter.getItem(0).setUserVisibleHint(isVisibleToUser);
            else
                mAdapter.getItem(0).setUserVisibleHint(false);
        }

        TaskExecutor.scheduleTaskOnUiThread(500, new Runnable() {
            @Override
            public void run() {
                if (mCurPager != null && mCurPager == PAGER_REMIND)
                    clearRemindRedTag();
            }
        });
    }

    @Override
    @EventTrace({EventID.APP_CUSTOMER_INDEX_CUSTOMER_CLICK, EventID.APP_CUSTOMER_INDEX_TIPS_CLICK})
    public void showPager(@EventTraceSelector int position) {
        if (mCurPager != null && mCurPager == position)
            return;

        mCurPager = position;
        mViewPage.setCurrentItem(mCurPager, true);
        tvAllCustom.setSelected(false);
        tvRemind.setSelected(false);

        switch (position) {
            case PAGER_ALL:
                tvAllCustom.setSelected(true);
                break;
            case PAGER_REMIND:
                clearRemindRedTag();
                tvRemind.setSelected(true);
                break;
        }
    }

    @Override
    public void showRedRemind(int count) {
        if (mCurPager == PAGER_REMIND && getUserVisibleHint()) {
            imgRemindNotice.setVisibility(View.INVISIBLE);
            NoticeManager.clickNoticeByCode(NoticeEntity.TypeBigDay);
        } else {
            imgRemindNotice.setVisibility(count > 0 ? View.VISIBLE : View.INVISIBLE);
        }
    }

    /* 清除提醒数据的红点 */
    private void clearRemindRedTag() {
        if (imgRemindNotice.isShown()) {
            imgRemindNotice.setVisibility(View.INVISIBLE);
            NoticeManager.clickNoticeByCode(NoticeEntity.TypeBigDay);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.customer_all:
                if (mCurPager == PAGER_ALL) {
                    clickAllCustom();
                } else {
                    showPager(PAGER_ALL);
                }
                break;
            case R.id.customer_remind:
                showPager(PAGER_REMIND);
                break;
            case R.id.btn_left:
                getActivity().finish();
                break;
        }
    }

    private long lastCustomAllClickTime;

    private void clickAllCustom() {
        long time = System.currentTimeMillis();
        if (time - lastCustomAllClickTime < Constants.HALF_SECOND && time - lastCustomAllClickTime > 0) {
            EventBus.getDefault().post(new CustomAllTopEvent());
        }
        lastCustomAllClickTime = time;
    }

    @Override
    public void onDestroy() {
        if (mAdapter != null) {
            for (int i = mAdapter.getCount(); i > 0; i--) {
                if (mAdapter.getItem(i - 1) != null)
                    mAdapter.getItem(i - 1).onDestroy();
            }
        }

        if (customersPresenter != null) {
            customersPresenter.onDestroy();
            customersPresenter = null;
        }

        super.onDestroy();
    }

}